package com.playball.lottery;

import java.io.File;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.HttpHandler;

import com.playball.lottery.customview.CustomDilogActivity;
import com.playball.lottery.nt.AppVersionConfig;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.Logger;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * down service
* @ClassName: DownService 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author vanszhen 
* @date 2014年7月16日 下午3:37:24 
*
 */

public class DownService extends Service {
	
	private ConnectivityManager connectivityManager;
	private NetworkInfo info;

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				Logger.d("van", "网络状态已经改变");
				connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				info = connectivityManager.getActiveNetworkInfo();
				if (info != null && info.isAvailable()) {
					String name = info.getTypeName();
					// 只在 wifi 下载
					if ("WIFI".equalsIgnoreCase(name)) {
						breakPointDown(url, apkName);
					}
					Logger.d("van", "当前网络名称：" + name);
				} else {
					Logger.d("van", "没有可用网络");
				}
			}
		}
	};
	//apk  name
	private String apkName ;
	// down url
	private String url;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mReceiver, mFilter);
		apkName = intent.getStringExtra("apkName");
		url=AppVersionConfig.UPDATE_SERVER+apkName;
	}
	
    private void breakPointDown(String url,String apkName){
		
		FinalHttp fh = new FinalHttp();
		File file = new File(Constants.APK_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}
		 @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
		HttpHandler	handown=fh.download(url, file + "/"  
			+apkName, false,new AjaxCallBack() {
			
			@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
				}
			
			 @Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
				int progressBarState = (int) (Float.parseFloat(Long
						.toString(current))
						/ Float.parseFloat(Long.toString(count)) * 100);
				//Log.d("tag",count +"--------"+current );
			}
			 @Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub
				 downHandler.sendEmptyMessage(0X001);
					super.onSuccess(t);
				}
			 @Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					super.onFailure(t, strMsg);
				}
			 
			});
	
	}
	
	
	Handler downHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0X001:
				InstallConfirm();
				break;
			default:
				break;
			}
			
		};
	};
	
	private void  InstallConfirm() {
		Intent intent = new Intent(this,CustomDilogActivity.class);
	    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    intent.putExtra("apkName", apkName);
		startActivity(intent);
/*		ShowCustomDialog dialog = new ShowCustomDialog.Builder(getApplicationContext()).setTitle("温馨提示")
				.setMessage("有新版本可以安装!")
				// 设置内容
				.setPositiveButton("取消",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						}).setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						updateAPK();
					}
				}).setMessageIcon(R.drawable.message_icon).createCustomDialog();
		dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();*/
	}
	
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
}
